package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.UserServiceImpl;
import com.xuanzheng.company.util.PasswordUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/updateUserProfile")
public class UserProfileServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        // 获取当前登录用户
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            out.print(gson.toJson(result));
            return;
        }

        User currentUser = (User) session.getAttribute("user");

        try {
            // 读取请求体中的JSON数据
            StringBuilder sb = new StringBuilder();
            String line;
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            // 解析JSON数据
            JsonObject jsonObject = JsonParser.parseString(sb.toString()).getAsJsonObject();
            
            // 获取表单参数
            String name = jsonObject.has("name") ? jsonObject.get("name").getAsString() : null;
            String gender = jsonObject.has("gender") ? jsonObject.get("gender").getAsString() : null;
            Integer age = jsonObject.has("age") ? jsonObject.get("age").getAsInt() : null;
            String phone = jsonObject.has("phone") ? jsonObject.get("phone").getAsString() : null;
            String email = jsonObject.has("email") ? jsonObject.get("email").getAsString() : null;
            String address = jsonObject.has("address") ? jsonObject.get("address").getAsString() : null;
            
            System.out.println("收到的用户资料更新请求: name=" + name + ", gender=" + gender + ", phone=" + phone);

            // 验证必填参数
            if (name == null || name.trim().isEmpty() || gender == null || gender.trim().isEmpty() || 
                age == null || age <= 0 || phone == null || phone.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "姓名、性别、年龄和手机号不能为空，年龄必须为正数");
                out.print(gson.toJson(result));
                return;
            }
            
            // 检查手机号是否已被其他用户使用
            User existingUser = userService.findByPhone(phone);
            if (existingUser != null && !existingUser.getId().equals(currentUser.getId())) {
                result.put("success", false);
                result.put("message", "该手机号已被其他用户使用");
                out.print(gson.toJson(result));
                return;
            }

            // 更新用户信息
            currentUser.setName(name);
            currentUser.setGender(gender);
            currentUser.setAge(age);
            currentUser.setPhone(phone);
            currentUser.setEmail(email != null ? email : "");
            currentUser.setAddress(address != null ? address : "");

            boolean updateSuccess = userService.updateUser(currentUser);

            if (updateSuccess) {
                // 更新会话中的用户对象
                session.setAttribute("user", currentUser);
                
                result.put("success", true);
                result.put("message", "个人资料更新成功");
                result.put("user", currentUser);
            } else {
                result.put("success", false);
                result.put("message", "个人资料更新失败，请稍后重试");
            }
        } catch (Exception e) {
            System.err.println("处理用户资料更新请求时发生错误: " + e.getMessage());
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "处理请求出错: " + e.getMessage());
        }

        out.print(gson.toJson(result));
    }
} 